import { useState, useEffect, useRef, createRef } from 'react';
import { Modal, Button, message, Image as AntdImage } from 'antd';
import styled from "@emotion/styled";
import { Icon } from '../form-generator/icon';

const canvasWidth = 588;
const canvasHeight = 192;

// canvas鼠标签名生成base64
export const Autograph = ({ value, onChange, ...rest }) => {
    const [visible, setVisible] = useState(false);
    const canvasRef = createRef();

    const startInfo = useRef();

    useEffect(() => {
        if (visible) {
            drawAction();
        } else {
            if (canvasRef.current) {
                canvasRef.current.onmousedown = null;
            }
        }
    }, [visible]);

    const drawAction = () => {
        canvasRef.current.onmousedown = (e) => {
            const rect = canvasRef.current.getBoundingClientRect();

            startInfo.current = {
                sx: e.clientX - rect.x,
                sy: e.clientY - rect.y,
                offsetx: rect.x,
                offsety: rect.y,
                ctx: canvasRef.current.getContext('2d')
            };

            canvasRef.current.onmousemove = onTouchMove;
            canvasRef.current.onmouseup = onTouchEnd;
            canvasRef.current.onmouseleave = onTouchEnd;
        }
    }
    // 移动 标签被拖动时
    const onTouchMove = (e) => {
        e.preventDefault();
        e.stopPropagation();
        if (!startInfo.current) return;

        const { sx, sy, ctx, offsetx, offsety } = startInfo.current;
        const x = e.clientX - offsetx;
        const y = e.clientY - offsety;

        ctx.beginPath();
        ctx.strokeStyle = '#000000';
        ctx.lineWidth = "3";
        ctx.lineCap = 'round'
        ctx.lineJoin = "round";

        ctx.moveTo(sx, sy);
        ctx.lineTo(x, y);

        ctx.stroke();
        ctx.closePath();

        // 保存新位置
        startInfo.current = {
            ...startInfo.current,
            sx: x,
            sy: y
        }
    };
    // 鼠标松开事件 包括鼠标移出事件
    const onTouchEnd = () => {
        // 移除掉所有鼠标事件回调
        canvasRef.current.onmousemove = null;
        canvasRef.current.onmouseup = null;
        canvasRef.current.onmouseleave = null;
        startInfo.current = null;
    };

    const onReset = () => {
        canvasRef.current.getContext('2d').clearRect(0, 0, canvasWidth, canvasHeight);
    }

    // 压缩
    const compress = (img, width = 440, height = 144) => new Promise((resolve, reject) => {
        const image = new Image();
        image.onload = () => {
            const canvasId = 'canvasBase64Imgid';
            let canvas = document.getElementById(canvasId);
            if (canvas !== null) document.body.removeChild(canvas);
            canvas = document.createElement("canvas");
            canvas.setAttribute('id', canvasId);
            canvas.style.display = 'none';
            canvas.width = width;
            canvas.height = height;
            document.body.appendChild(canvas);
            const ctx = canvas.getContext('2d');

            ctx.drawImage(image, 0, 0, width, height);
            const imgDataURL = canvas.toDataURL('image/png', 1);
            resolve(imgDataURL);
        }
        image.src = img;
    })

    const onSubmit = async () => {
        const ctx = canvasRef.current.getContext('2d');
        const imageData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
        // 有色值的像素点个数
        if (imageData.data.filter(srgb => !!srgb).length <= 200) {
            return message.error('请书写完整签名');
        }

        const originImg = canvasRef.current.toDataURL('image/png');

        const imgCompressed = await compress(originImg);
        onChange && onChange(imgCompressed);
        setVisible(false);
    }

    return (
        <>
            <Container className={rest.disabled ? 'disabled' : ''} onClick={() => {
                if (rest.disabled || rest.readonly) return;

                setVisible(true);
            }}>
                {
                    rest.readonly ? (
                        <AntdImage className="img" src={value} alt="签名" />
                    ) : value ? (
                        <img className="img" src={value} alt="签名" />
                    ) : (
                        <div className="placeholder">
                            <Icon type="autograph" />
                            <span className="holder-text">添加签名</span>
                        </div>
                    )
                }
            </Container>
            <Modal
                title="设置签名"
                width={640}
                visible={visible}
                footer={null}
                onCancel={() => setVisible(false)}
            >
                <canvas
                    ref={canvasRef}
                    id="autographCanvas"
                    width={canvasWidth}
                    height={canvasHeight}
                    style={{ border: '2px dashed #ccc' }}
                />
                <FooterBottons>
                    <Button onClick={onReset}>重置</Button>
                    <Button type="primary" onClick={onSubmit}>提交</Button>
                </FooterBottons>
            </Modal>
        </>
    );
}

const Container = styled.div`
    &.disabled {
        cursor: not-allowed;
    }
    .img {
        width: 220px;
        height: 72px;
        max-width: 100%;
    }
    .placeholder {
        color: #666;
        border: 1px dashed #ccc;
        width: 220px;
        max-width: 100%;
        height: 72px;
        line-height: 72px;
        text-align: center;
    }
`
const FooterBottons = styled.div`
    text-align: right;
    & > button {
        width: 100px;
        margin-left: 10px;
    }
`